package com.chuantou.yuba.ui;

import java.util.HashMap;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.UiUtil;

/**
 * 修改密码界面
 * 
 * @author dl1001
 * 
 */
public class ChangePasswordActivity extends BaseActionBarActivity implements OnClickListener, TextWatcher {
	private static final int WHAT_REMOVE_ERROR_MSG = 0x1;
	private TextView mErrorView;
	private EditText mOldPwdView;
	private EditText mNewPwdView;
	private EditText mRePwdView;
	private TextView mSubmitBtnView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.change_password);
		setupViews();
		setTitle(R.string.change_password);
	}

	private void setupViews() {
		mErrorView = (TextView) findViewById(R.id.message);
		mOldPwdView = (EditText) findViewById(R.id.old_password);
		mOldPwdView.addTextChangedListener(this);
		mNewPwdView = (EditText) findViewById(R.id.password);
		mNewPwdView.addTextChangedListener(this);
		mRePwdView = (EditText) findViewById(R.id.repassword);
		mRePwdView.addTextChangedListener(this);
		mSubmitBtnView = (TextView) findViewById(R.id.submit);
		mSubmitBtnView.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.submit:
			changePassword();
			break;

		default:
			break;
		}
	}

	private void changePassword() {
		if (UiUtil.isFastDoubleClick())
			return;
		String newPassword = mNewPwdView.getText().toString();
		if (newPassword.length() < 6) {
			showErrorMessage(getString(R.string.input_new_password_error));
			return;
		}
		String rePassword = mRePwdView.getText().toString();
		if (!newPassword.equals(rePassword)) {
			showErrorMessage(getString(R.string.input_repassword_error));
			return;
		}
		String oldPassword = mOldPwdView.getText().toString();
		if (oldPassword.equals(newPassword)) {
			showErrorMessage(getString(R.string.intput_new_password));
			return;
		}
		AccountManager accountManager = AccountManager.getInstance(getApplicationContext());
		if (!accountManager.isLogined()) {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
			return;
		} else {
			UserTO user = accountManager.getUserTO();
			if (user.isExpired()) {
				Toast.makeText(this, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
				LoginActivity.start(this, -1, LoginActivity.ACTION_RETURN);
			} else {
				final ProgressDialog dialog = new ProgressDialog(this);
				dialog.setMessage(getString(R.string.submiting));
				dialog.setCancelable(false);
				dialog.show();
				String url = UriHelper.getChangePasswordUrl();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(UriHelper.PARAMS_TOKEN, user.getToken());
				params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
				params.put(UriHelper.PARAMS_OLD_PASS, oldPassword);
				params.put(UriHelper.PARAMS_NEW_PASS, newPassword);
				GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

					@Override
					public void onResponse(BaseTO response) {
						if (!hasDestroyed()) {
							dialog.dismiss();
							if (response != null) {
								if (response.isSuccess()) {
									Toast.makeText(getApplicationContext(), R.string.change_password_success, Toast.LENGTH_SHORT).show();
									onBackPressed();
								} else {
									if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
										Toast.makeText(getApplicationContext(), R.string.message_token_expired, Toast.LENGTH_SHORT).show();
										LoginActivity.start(ChangePasswordActivity.this, -1, LoginActivity.ACTION_RETURN);
									} else {
										String msg = response.getMsg();
										msg = TextUtils.isEmpty(msg) ? getString(R.string.change_password_failed) : msg;
										showErrorMessage(msg);
									}
								}
							} else {
								showErrorMessage(getString(R.string.change_password_failed));
							}
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (!hasDestroyed()) {
							dialog.dismiss();
							showErrorMessage(getString(R.string.request_error));
						}
					}
				}, params, BaseTO.class);
				RequestManager.startRequest(getApplicationContext(), request);
			}
		}
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case WHAT_REMOVE_ERROR_MSG:
				mErrorView.setVisibility(View.GONE);
				break;

			default:
				break;
			}
		};
	};

	private void showErrorMessage(String msg) {
		mHandler.removeMessages(WHAT_REMOVE_ERROR_MSG);
		mErrorView.setVisibility(View.VISIBLE);
		mErrorView.setText(msg);
		mHandler.sendEmptyMessageDelayed(WHAT_REMOVE_ERROR_MSG, 1500);
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

	@Override
	public void afterTextChanged(Editable s) {
		boolean enable = hasText(mNewPwdView) && hasText(mOldPwdView) && hasText(mRePwdView);
		mSubmitBtnView.setEnabled(enable);

	}

	private boolean hasText(EditText editText) {
		return !TextUtils.isEmpty(editText.getText());
	}

}
